﻿using Autofac;
using System.Reflection;
using System.Text.RegularExpressions;

namespace TPWorkPlat.Server
{
    public class AutofacModuleRegister : Autofac.Module
    {
        protected override void Load(ContainerBuilder containerBuilder)
        {
            string[] assemblyScanerPattern = new[] { @"TPWorkPlat.*.Service.dll", @"TPWorkPlat.*.Repository.dll" };

            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

            List<Assembly> assemblies = new List<Assembly>();
            assemblies.AddRange(
                Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*.dll", SearchOption.AllDirectories)
                         .Where(filename => assemblyScanerPattern.Any(pattern => Regex.IsMatch(filename, pattern)))
                         .Select(Assembly.LoadFrom)
                );

            foreach (var assembly in assemblies)
            {
                containerBuilder.RegisterAssemblyTypes(assembly).Where(t => t.Name.EndsWith("Service") || t.Name.EndsWith("Repository"))
                    .AsImplementedInterfaces().AsSelf();
            }
        }
    }
}
